    // templates/salesman/pages/bindingorder/bindingorder.js

    import Dialog from '@vant/weapp/dialog/dialog';
    import Toast from '@vant/weapp/toast/toast';
    import Notify from '@vant/weapp/notify/notify';
    import {clearUserLocalStorage} from "../../../../utils/util";

    const app = getApp();
    Page({

        /**
         * 页面的初始数据
         */
        data: {
            orders: [], //订单
            longitude: 0, //经纬度
            latitude: 0,
            access_token: undefined,
            user: undefined,
            user_id: undefined,
            view_public: 0,
            is_pay: 1,

            show_search_bar: true,
            search_word:'',

            //弹出框的ID和备注名
            popup_remark_id: 0,
            popup_remark_name: '',
            popup_idx: 0,

            //页码
            page: 0,
            //每页条目
            page_size: 10,




            orderAll: [], //数据

            default_image: '/templates/salesman/img/business.png', //地图图标

            id: 0, //司机id
            username: '', //司机姓名
            show: true, //控制加载动画
            activeNames: ['0'], //点击折叠
            ball: false, //控制弹出层
            fileList: [], //图片集合
            imgCount: 3, //设置上传图片数量
            controlUpload: true, //控制文件上传
            imgDelete: true, //控制文件删除
            buttstatus: 1, //点击提交按钮禁用
            imgMax: 1048576 * 2, //单图片大小
            order_id: 0,
            values: '',
            ordername: '', //收货人
            status: false, //状态是不是有数据
            result: [], //控制获取的数据
            checkedAll: false, //控制全选
            dshow: true, // 控制送达栏目
        },

        /**
         * 点击打开
         */
        onChange(event) {
            console.log(event.detail)
            this.setData({
                activeNames: event.detail,
            });
        },
        call_mobile(e) {
            let mobile = e.currentTarget.dataset.mobile + ''
            wx.makePhoneCall({
                phoneNumber: mobile,
                success: function () {
                    console.log("拨打电话成功！")
                },
                fail: function () {
                    console.log("拨打电话失败！")
                }
            })
        },

        /**
         * 生命周期函数--监听页面加载
         */
        onLoad(options) {
            let that = this
            let now = (new Date().getTime()) / 1000;
            let expiration_time = wx.getStorageSync('expiration_time')
            let group = wx.getStorageSync('role')

            if (group!=='销售员') {
                clearUserLocalStorage()
                expiration_time = 0
            }

            if (now > expiration_time) {
                wx.reLaunch({
                    url: '/pages/login/login',
                })
            }



            let access_token =  wx.getStorageSync('access_token')
            let user = wx.getStorageSync('user')
            let data ={
                'access_token': access_token,
                'user': user
            }

            let user_id = options.user_id;
            if (user_id) {
                data['user_id'] = user_id;
            }

            let current_share_id = wx.getStorageSync('current_share_id')
            if (current_share_id) {
                data['current_share_id'] = current_share_id
            }
            let is_pay = options.is_pay
            if (is_pay) {
              data['is_pay'] = options.is_pay
          }

            this.setData(data)

            //获取当前定位
            wx.getLocation({
                type: "gcj02",
                success: res => {
                    console.log( 'res', res)
                    that.setData({
                        latitude: res.latitude,
                        longitude: res.longitude,
                    })

                    this.get_orders().then(r => {})
                }
            })

            //接收上级传递的参数
            // const eventChannal = this.getOpenerEventChannel();
            // eventChannal.on('orderAll', function (res) {
            //     let orderAll = JSON.parse(res)
            //     this_.setData({
            //         orderAll
            //     })
            //     console.log(orderAll)
            // })

        },

        on_navigate(e) {
            let name = e.currentTarget.dataset.name // 获取用户信息
            let address = e.currentTarget.dataset.address //获取配送地址
            let latitude = e.currentTarget.dataset.latitude //获取经纬度
            let longitude = e.currentTarget.dataset.longitude
            wx.openLocation({
                name: name,
                address: address,
                latitude: Number(latitude),
                longitude: Number(longitude),
            })
        },

        update_customer_remark(e) {
            console.log(e.detail)
            let that = this
            let user_id = e.detail.value.user_id //获取id
            let remark_name = e.detail.value.remark_name

            let status = e.detail.target.id //获取按钮id

            wx.p.request({
                url: app.globalData.API + '/sales/index/update-customer-remark',
                header: {
                    'Content-Type': 'application/json',
                    "x-api-key": this.data.access_token,
                },
                method: "POST",
                data: {
                    user_id: user_id,
                    remark_name: remark_name, //传递商城id
                },
                success(res) {
                    if (res.data.code === 200) {
                        let idx = that.data.popup_idx
                        let customers = that.data.customers
                        customers[idx]['remark_name'] = remark_name
                        that.setData({
                            customers: customers,
                            ball: false,
                        })
                        Notify({
                            type: 'success',
                            message: '加载完成~~'
                        });

                    } else if (res.data.code === 0) {
                        clearUserLocalStorage()
                        wx.reLaunch({
                            url: "/pages/login/login"
                        })
                    }
                },
                fail() {
                    wx.showToast({
                        title: '请求错误',
                        icon: 'error',
                        duration: 2000
                    })
                },
            })
        },


        /**
         * 弹出层控制
         */
        ballPopup(e) {
            console.log(e)
            let popup_remark_id = e.currentTarget.dataset.user_id //获取传递的id参数
            let popup_remark_name = e.currentTarget.dataset.remark_name
            let popup_idx = e.currentTarget.dataset.idx
            this.setData({
                ball: true,
                popup_remark_id: popup_remark_id,
                popup_remark_name: popup_remark_name,
                popup_idx: popup_idx
            }) //打开弹窗
        },

        ball_pop_down() {
            this.setData({
                ball: false,
            })
        },

        /**
         * 关闭弹出层控制
         */
        onClose() {
            this.setData({
                fileList: [],
                values: '',
                ball: false,
                dshow: true
            })
        },
        /**
         * 生命周期函数--监听页面初次渲染完成
         */
        onReady() {

        },

        /**
         * 生命周期函数--监听页面显示
         */
        onShow() {

        },

        /**
         * 生命周期函数--监听页面隐藏
         */
        onHide() {

        },

        /**
         * 生命周期函数--监听页面卸载
         */
        onUnload() {

        },

        /**
         * 页面相关事件处理函数--监听用户下拉动作
         */
        onPullDownRefresh() {
            let that = this
            setTimeout(function () {
                that.get_orders().then(r => {

                })
            }, 2000);
            wx.stopPullDownRefresh()
        },

        /**
         * 页面上拉触底事件的处理函数
         */
        onReachBottom() {
            let that = this
            this.get_orders()

        },

        /**
         * 用户点击右上角分享
         */
        onShareAppMessage() {

        },


        make_mark(customer){
            return {
                id: Number(customer.address.id),
                width: 16,
                height: 16,
                latitude: Number(customer.address.latitude),
                longitude: Number(customer.address.longitude),
                iconPath: "../../img/icon-hc.png",
                callout: {
                    content: customer.address.name,
                    fontSize: 14,
                    padding: true,
                    color: '#ffffff',
                    display: 'ALWAYS',
                    textAlign: 'center',
                    borderRadius: 10,
                    bgColor: '#0077ffbe'
                },
            }
        },

        on_search_word_change(e) {
            this.setData({
                search_word: e.detail
            });
        },

        do_search() {
            this.setData({
                markers: [],
                customers: [],
                page: 0
            })
            console.log(this.data.search_word)
            this.get_orders()
        },

        async get_orders() {
            let that = this
            let user_id = that.data.user_id
            if (!user_id) {
                user_id = ''
            }
            wx.p.request({
                url: app.globalData.API + '/sales/index/get-user-orders' +
                    '?page=' +  that.data.page +
                    '&per-page=' + that.data.page_size,
                header: {
                    'Content-Type': 'application/json',
                    "x-api-key": this.data.access_token,
                },
                method: "POST",
                data: {
                    user_id: user_id, //传递商城id
                    is_pay: that.data.is_pay,
                    latitude: that.data.latitude,
                    longitude: that.data.longitude,
                    current_share_id: that.data.current_share_id,
                },
                success(res) {
                    if (res.data.code === 200) {
                        let orders = res.data.data.data
                        for(let i=0;i<orders.length;i++) {
                            for (let j = 0;j<orders[i].orderDetail.length;j++) {
                                orders[i].orderDetail[j].goods_info =
                                    JSON.parse(orders[i].orderDetail[j].goods_info);
                            }
                        }

                        let page = that.data.page + 1
                        orders = that.data.orders.concat(orders)
                        that.setData({
                            show: false,
                            orders: orders,
                            page: page
                        })


                        wx.setNavigationBarTitle({
                            title: '订单信息'
                        })

                        Notify({
                            type: 'success',
                            message: '加载完成~~'
                        });

                    } else if (res.data.code === 0) {
                        clearUserLocalStorage()
                        wx.reLaunch({
                            url: "/pages/login/login"
                        })
                    }
                },
                fail() {
                    wx.showToast({
                        title: '请求错误',
                        icon: 'error',
                        duration: 2000
                    })
                },
            })
        },

        //根据距离计算远近
        sortArr(newArray) {
            var arr = newArray;
            var s = "";
            for (var i = 1; i < arr.length; i++) {
                for (var j = i; j > 0; j--) {
                    if (arr[j].resKm > arr[j - 1].resKm) {
                        s = arr[j];
                        arr[j] = arr[j - 1];
                        arr[j - 1] = s;
                    }
                }
            }
            return newArray.reverse();
        },

        sort_customers_by_distance(newArray) {
            var arr = newArray;
            var s = "";
            for (var i = 1; i < arr.length; i++) {
                for (var j = i; j > 0; j--) {
                    if (arr[j].distance > arr[j - 1].distance) {
                        s = arr[j];
                        arr[j] = arr[j - 1];
                        arr[j - 1] = s;
                    }
                }
            }
            return newArray.reverse();
        },

        get_current_distance(lat2, lng2) {
            let lat1 = this.data.latitude
            let lng1 = this.data.longitude
            console.log('距离1:',lat1, lng1)

            console.log('距离2:',lat2, lng2)

            var radLat1 = lat1 * Math.PI / 180.0;
            var radLat2 = lat2 * Math.PI / 180.0;
            var a = radLat1 - radLat2;
            var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
            var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
            s = s * 6378.137; // EARTH_RADIUS;
            s = Math.round(s * 10000) / 10000;
            s = s.toFixed(2);
            return parseFloat(s);
        },

        // 经纬度计算距离
        get_distance(lat1, lng1, lat2, lng2) {
            console.log('距离1:',lat1, lng1)

            console.log('距离2:',lat2, lng2)

            var radLat1 = lat1 * Math.PI / 180.0;
            var radLat2 = lat2 * Math.PI / 180.0;
            var a = radLat1 - radLat2;
            var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
            var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
            s = s * 6378.137; // EARTH_RADIUS;
            s = Math.round(s * 10000) / 10000;
            s = s.toFixed(2);
            return parseFloat(s);
        },
        /**
         * 点击全选 订单全部送达
         */
        onClickUpdate(event) {
            let this_ = this
            //弹窗提醒
            Dialog.confirm({
                title: '确认送达？',
                message: '是否确定？全部送达？',
              })
                .then(() => {
                  // on 确定提交
                    let resultAll = this.data.result
                    let arr = []
                    let url = app.globalData.URL
                    let mall_id = app.globalData.mall_id
                    for(let i=0 ; i< resultAll.length; i++){
                        arr.push(Number(resultAll[i]))
                    }
                  wx.request({
                    url: url + '/salesman.Order/getIdAllUpdate',
                    method: "POST",
                    dataType: "json",
                    header:{ },
                    data: {
                        mall_id,
                        arr
                    },
                    success: res=>{
                        console.log(res)
                        if(res.data.code === 0 ){
                            Toast('送达成功');
                            this_.setData({
                                result: []
                            })
                            this_.driverOrderAll()
                        }else{
                            Toast('送达失败');
                        }
                    },
                    fail(s){
                        //调用失败
                        Toast('系统异常');
                    },
                    complete(r){
                        //成功失败都调用
                    }
                  })
                })
                .catch(() => {
                  // on 取消
                  Notify({ type: 'warning', message: '取消送达' });
                });
        }



    })
